package com.atguigu.gulimall.order.config;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * Feign请求的拦截器，用于增加请求头携带登录信息
 *
 * @author LaiSanShan
 * @date 2021-08-31
 */
@Configuration
public class GulimallFeignConfig {

    @Bean("requestInterceptor")
    public RequestInterceptor requestInterceptor() {
        return new RequestInterceptor() {

            /**
             * Called for every request. Add data using methods on the supplied {@link RequestTemplate}.
             *
             * @param template 原始请求模板
             */
            @Override
            public void apply(RequestTemplate template) {
                // 获取当前请求
                ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
                if (requestAttributes != null) {
                    HttpServletRequest request = requestAttributes.getRequest();
                    // 同步当前请求信息的cookie到Feign请求
                    template.header("Cookie", request.getHeader("Cookie"));
                }
            }
        };
    }

}
